//
//  JoinViewController.swift
//  jiahui
//
//  Created by 3tee on 2024/11/21.
//

import UIKit
import Moya
import RxSwift
import CryptoSwift
import MBProgressHUD
import avd_sdk

class JoinViewController: UIViewController {
    let provider = MoyaProvider<RestAPI>(plugins:[NetworkLoggerPlugin(),ReqActivity(showHud: true)])
    typealias loginSuccessClosure = (_ model :LoginModel) -> Void
    let bag = DisposeBag()
    @IBOutlet weak var settingBtn: UIButton!
    @IBOutlet weak var scrollerview: UIScrollView!
    
    @IBOutlet weak var pageControl: UIPageControl!
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        navigationController?.setNavigationBarHidden(true, animated: true)

    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()

        // Do any additional setup after loading the view.
    }
    
    
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navigationController?.setNavigationBarHidden(false, animated: true)

    }
   
    

    
    func setupUI() {
    
        scrollerview.contentSize = CGSize(width: UIScreen.main.bounds.size.width * 3, height: scrollerview.frame.height)
        scrollerview.delegate = self
        scrollerview.isPagingEnabled = true
        scrollerview.showsHorizontalScrollIndicator = false
        print("scroller h = \(scrollerview.frame.height)")
        addDispalyImg()
        self.view.bringSubviewToFront(self.settingBtn)
        let aftertime: DispatchTimeInterval = .seconds(1)
        let deadline = DispatchTime.now() + aftertime
        
//        DispatchQueue.main.asyncAfter(deadline: deadline, execute: DispatchWorkItem(block: {
//            print("延迟一秒执行")
//            
//        }))
        let firstInstall = UserDefaultsPlugin.bool(forKey: Constant.key_firstInstall)
        if !firstInstall {
            let privacy = PrivacyView.loadXib()
            privacy.frame = view.bounds
            //view.addSubview(privacy)
            UIApplication.shared.keyWindow?.addSubview(privacy)
        }
       
        
    }
    
    func addDispalyImg() {
        pageControl.numberOfPages = 3
        for idx in 1...3 {
            let imgW =  UIScreen.main.bounds.width
            let imgv = UIImageView(frame: CGRect(x: CGFloat((0 + idx - 1)) * imgW, y: 0, width:imgW , height: scrollerview.frame.size.height))
             imgv.image = UIImage(named: "start_page_\(idx)")
             scrollerview.addSubview(imgv)
        }
    }

    
    @IBAction func loginClicked(_ sender: UIButton) {
        let alertVC = UIAlertController(title: "用户登陆", message: nil, preferredStyle: .alert)
        alertVC.addTextField { nameTf in
            nameTf.placeholder = "请输入用户名"
            if let name = UserDefaults.standard.string(forKey: Constant.key_name){
                nameTf.text = name
            }
        }
        alertVC.addTextField { pwdTf in
            pwdTf.placeholder = "请输入密码"
            pwdTf.isSecureTextEntry = true
            if let pwd = UserDefaults.standard.string(forKey: Constant.key_pwd){
                pwdTf.text = pwd
            }
        }
        alertVC.addAction(UIAlertAction(title: "取消", style: .cancel, handler: { action in
            
        }))
        alertVC.addAction(UIAlertAction(title: "登录", style: .default, handler: { [self] action in
            let nameTf = alertVC.textFields?.first
            let pwdmd5 = alertVC.textFields?.last?.text?.md5()
            if let nameRsa = RSA.encryptString(nameTf?.text, publicKey: RSA_Public_key) , let pwdRsa = RSA.encryptString(pwdmd5, publicKey: RSA_Public_key) {
                print("name rsa加密 = \(nameRsa) \n pwd = \(pwdRsa)")

                reqLogin(name: nameRsa, pwd: pwdRsa, loginBlcok: { model in
                    if model.ret == 0{
                        UserDefaults.standard.setValue(nameTf?.text, forKey: Constant.key_name)
                        UserDefaults.standard.setValue(alertVC.textFields?.last?.text, forKey: Constant.key_pwd)
                        UserDefaults.standard.setValue(true, forKey: Constant.key_isLogin)
                        UserDefaults.standard.synchronize()
                        print("登陆成功")
                        let modelData = try? JSONEncoder().encode(model)
                        //UserDefaults.standard.setValue(modelData, forKey: Constant.key_loginModel)
                        UserDefaultsPlugin.setValue(modelData, key: Constant.key_loginModel)
                        let tabbarVC = MainTabBarController()
                        tabbarVC.lgoinModel = model
                        self.navigationController?.pushViewController(tabbarVC, animated: true)
                    }
                })
              
            }
        }))
        self.present(alertVC, animated: true)
    }
 
    
    
    @IBAction func go2Setting(_ sender: UIButton) {
        
        let storyboard = UIStoryboard(name: "SettingViewController", bundle: .main)
        let vc = storyboard.instantiateViewController(withIdentifier:"SettingViewController")
        self.navigationController?.pushViewController(vc, animated: true)
        
    }
    
    
    @IBAction func go2joining(_ sender: UIButton) {
        self.navigationController?.pushViewController(JoiningViewController(), animated: true)
    }
    
    func reqLogin(name: String, pwd: String, loginBlcok: @escaping loginSuccessClosure){
//        let encodename = "dOs9Qzx5DjI4cNq9d80KHIdNPhZvC4L5DDOES8kC3oQu+fahwS7k4FAysaYDAl+cBPnuzfcYbQaSdpch3ELgVG5X/FTdwzj1XlohzyPiMWyA5Ho/CEEIIVo1gzR7hhlNBccxNFV5p7Qjg3jXdX3ZhOHsXMLFEuXZ04mTmaNbh+E="
//       let encodepwd = "eVRdFtUB8Qi2Frqe6HGiN9RBgC6yFbRIypZHXWcjnRgdWQ/f8y2XAlYQFRGG78BaSLgi0MkoiS1riF2ixajQYY1YQOK4bWwitbaBwbu18N9MxhmPHb7vQRI5NkdQUb4lMnihcfd6ZUEot4TMScEiLc3+DaNU3favXPYdTGCQfG0="
//rxswift
         provider.rx.request(.login(email: name, pwd: pwd))
            .filterSuccessfulStatusCodes()
            .map(LoginModel.self)
            .asObservable()
            .subscribe { model in
                loginBlcok(model)
            }.disposed(by: bag)

    }
    
    func reqLogin(name: String,pwd: String,complete: @escaping loginSuccessClosure) -> Void {
        //moya
                provider.request(.login(email: name, pwd: pwd)) { result in
                    switch result{
                    case .success(let rep):
                         let code = rep.statusCode
                        let data = rep.data
                        do {
                               let loginModel = try JSONDecoder().decode(LoginModel.self, from: data)
                               print("解码成功：\(loginModel)")
                            complete(loginModel)
                           } catch {
                               print("解码失败：\(error)")
                           }
       //                 let json = try? JSONSerialization.jsonObject(with: data)
       //                 print("用户登陆json = \(json)")
       //                 do {
       //                     if let jsonDictionary = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
       //                         // jsonDictionary是一个字典，包含了JSON数据
       //                         complete(jsonDictionary)
       //
       //                         print(jsonDictionary)
       //                     }
       //                 } catch {
       //                     print("JSON解析失败: \(error)")
       //                 }
       
                    case .failure(let error):
                        print("login error = \(error)")
                    }
                }
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        //testGCD()
        //testGCDConcurrent()
        //testGroupNoti()
    }

    
    func testGCD() {
       let serialQueen = DispatchQueue(label: "serial")
        serialQueen.async {
            print("1")
        }
        serialQueen.async {
            print("2")
        }
    }
    func testGCDConcurrent() {
        let serialQueen = DispatchQueue(label: "serial")
        serialQueen.sync {
            print("1 thread = \(Thread.current)")
        }
        serialQueen.sync {
            print("2 thread = \(Thread.current)")
        }
        serialQueen.sync {
            print("3 thread = \(Thread.current)")
        }
        serialQueen.sync {
            print("4 thread = \(Thread.current)")
        }
        serialQueen.sync {
            print("======= thread = \(Thread.current) ======")
        }
    }
    
    func testGolbal() {
       let queen = DispatchQueue.global(qos: .default)
        queen.async {
            print("1")
        }
        queen.async {
            print("2")
        }
        queen.async {
            print("3")
        }
        queen.async {
            print("4")
        }
    }
    
    func testGroup() {
        let groupD = DispatchGroup()
        let groupE = DispatchGroup()
        let groupF = DispatchGroup()

        groupD.enter()
        DispatchQueue.global().async {
            for i in 0...3{
                print("aaaaa \(i)")
            }
            groupD.leave()
        }
        
        groupD.enter()
        groupE.enter()
        DispatchQueue.global().async {
            for i in 0...3{
                print("bbbb \(i)")
            }
            
            groupD.leave()
            groupE.leave()
        }
        
      
       
        
        
        groupE.enter()
        groupD.notify(queue: .main) {
            DispatchQueue.global().async {
                for i in 0...3{
                    print("dddd \(i)")
                }
                groupE.leave()
            }
        }
        
        groupF.enter()
        groupE.notify(queue: .main) {
            DispatchQueue.global().async {
                for i in 0...3{
                    print("eeee \(i)")
                }
                groupF.leave()
            }
        }
        
        groupE.notify(queue: .main) {
            DispatchQueue.global().async {
                for i in 0...3{
                    sleep(1)
                    print("cccc \(i)")
                    
                }
            }
        }
        
        groupF.notify(queue: .main) {
            DispatchQueue.global().async {
                for i in 0...3{
                    print("ffff \(i)")
                }
            }
        }
        
 
    }
    
}

func testGroupNoti(){
    // 创建一个 DispatchGroup 来管理任务
    let operationA = BlockOperation {
        performTask(name: "任务 a") {
            print("任务 a 完成")
        }
    }
    
  
    
    let operationB = BlockOperation {
        performTask(name: "任务 b") {
            print("任务 b 完成")
        }
    }
    
    let operationC = BlockOperation {
        performTask(name: "任务 C") {
            print("任务 C 完成")
        }
    }
    
    let operationD = BlockOperation {
        performTask(name: "任务 d") {
            print("任务 d 完成")
        }
    }
    
    let operationE = BlockOperation {
        performTask(name: "任务 e") {
            print("任务 e 完成")
        }
    }
    
    let operationF = BlockOperation {
        performTask(name: "任务 f") {
            print("任务 f 完成")
        }
    }
    let operationQ = OperationQueue()

    
    operationQ.addOperation(operationA)
    operationQ.addOperation(operationB)
    operationQ.addOperation(operationC)
  
    
    operationF.addDependency(operationA)
    operationF.addDependency(operationC)
    
    operationE.addDependency(operationA)
    operationE.addDependency(operationB)

    operationD.addDependency(operationF)
    operationD.addDependency(operationE)
    
   
    operationQ.addOperation(operationD)
    operationQ.addOperation(operationE)
    operationQ.addOperation(operationF)

    // aa bb cc ee ff  dd

    // 定义一个方法来模拟任务的执行
    func performTask(name: String, completion: @escaping () -> Void) {
        DispatchQueue.global().async {
            // 模拟网络请求或其他耗时操作
            sleep(1) // 模拟任务耗时
            print("\(name) 开始")
            completion()
        }
    }

}


extension JoinViewController: UIScrollViewDelegate{
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        let offset = scrollView.contentOffset
        
        let idx = Int(ceil(offset.x / screen_width))
        pageControl.currentPage = idx
        print("当前scorller idx = \(idx)")

    }
}



